class TopicsController < ApplicationController
  before_filter :set_nav_session
  before_filter :login_required, :except => [:show]
  
  def new
    @group = Group.find(params[:group_id])
    @topic = Topic.new
  end
  
  def create
    @group = Group.find(params[:group_id])
    @topic = Topic.new(params[:topic])
    @topic.group = @group
    @topic.user = current_user
    @topic.save!
    flash[:notice] = "写了新文章：#{@topic.title}"
    redirect_back_or_default(group_url(@group.id))
  end
  
  def edit
    @group = Group.find(params[:group_id])
    @topic = Topic.find(params[:id])
  end
  
  def update
    @group = Group.find(params[:group_id])
    @topic = Topic.find(params[:id])
    @topic.update_attributes!(params[:topic])
    flash[:notice] = "你修改了\"#{@topic.title}\""
    redirect_back_or_default(topic_url(@group.id, @topic.id))
  end
  
  def destroy
    @group = Group.find(params[:group_id])
    @topic = Topic.find(params[:id])
    if @topic.destroy
      flash[:notice] = "你删除了\"#{@topic.title}\""
      redirect_back_or_default(group_url(@group.id))
    else
      redirect_back_or_default(topic_url(@group.id, @topic.id))
    end
  end
  
  def show
    @group = Group.find(params[:group_id])
    @topic = Topic.find(params[:id], :include => :user)
    @posts = @topic.posts
    @post = Post.new
  end
  
  private
  def set_nav_session
    session[:nav] = "groups"
  end
end
